#include<at89c51ed2.h>
#include<mcs51reg.h>
#include<stdio.h>
#include "spi.h"
#include "io.h"


void delay(unsigned char time){
	while(time>0){
		time--;
	}
}

void sstDataReadRegisterSet(int reg_addr) //similar to spi data read, but does not release chip select,must be done manaually
{
	
	int txDummy;
	int ack;
	volatile int dataStatus; /*force control to check SPIF each time*/
	int i;
	
	ack=1;
	txDummy=0;
	i=0; //counter for multibyte read
	 
	

	/*send register address*/
	SPDAT=reg_addr;		/*put data in SPDAT for spi transfer*/
	dataStatus=SPSTA;
	dataStatus&=0x80;
	
	while(dataStatus==0)
	{
		dataStatus=SPSTA;
		dataStatus&=0x80;
	}
	
	/*end of transmitting register address*/
  /****************************************************************/
	   	
}
	
	
int sstDataReadVal()//reads 1 byte per call
{
	int rxData;
	unsigned char txDummy;
	volatile unsigned char dataStatus; /*force control to check SPIF each time*/
	
	
	
	txDummy=0xFF;
	SPDAT=txDummy;		/*put data in SPDAT for spi transfer*/

	
	dataStatus=SPSTA;
	dataStatus&=0x80;
	
	while(dataStatus==0)
	{
		dataStatus=SPSTA;
		dataStatus&=0x80;
	}

	
		rxData=SPDAT; /*transfer received data*/	

	return rxData;		/*return data*/
	
}
	

	
void chipErase()
{
	
	Master_spi_init(2); //for memory  chip*/
/****WREN enable**/
	spiChipSelectON(2);
	sstDataReadRegisterSet(0x06);//enable WREN
	spiChipSelectOFF(2);
	
	
	spiChipSelectON(2);
	spi_dataSend(0x50);//enable EWSR (Enable Write Status register)
	spiChipSelectOFF(2);


	spiChipSelectON(2);
	sstDataReadRegisterSet(0x01); //enable WRSR
	spi_dataSend(0x02);//write to write status register, WEL bit should go to zero, expected value 00
	spiChipSelectOFF(2);
	
	
	/****WREN enable**/
	spiChipSelectON(2);
	sstDataReadRegisterSet(0x06);//enable WREN, make WEL=1;
	spiChipSelectOFF(2); 
	
	spiChipSelectON(2);
	sstDataReadRegisterSet(0x60);//erase chip
	spiChipSelectOFF(2);
	
	
	
		while((spi_dataRead(0x05,2)&0x01)==1)
	{
		printf("im here%d",spi_dataRead(0x05,2));
	}
	
	Master_spi_init(1); //for rssi chip, restored*/
}
	
	
	
		
